<template>
  <Dialog :title="title" :visible="visible" class="single-column" :loading="loading" button-text="保存" @close="close" @confirm="confirm">
    <!-- 新增修改回访规则 -->
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="回访类型:" prop="returnVisitTypeId">
        <el-select v-model="ruleForm.returnVisitTypeId" filterable placeholder="请选择回访类型" class="el-select-y" @change="typeChange">
          <el-option
            v-for="item in returnVisitList"
            :key="item.returnVisitTypeId"
            :label="item.type"
            :value="item.returnVisitTypeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回访时间:" prop="returnDay">
        {{ ruleForm.typeTemplate }}第 <el-input v-model="ruleForm.returnDay" style="width:46px" /> 天
      </el-form-item>
      <el-form-item v-if="ruleForm.returnVisitMan" label="回访人:" prop="returnName">
        <el-radio-group v-model="ruleForm.returnName">
          <el-radio v-for="(item,index) in ruleForm.returnVisitMan.split('，')" :key="index" :label="item">{{ item }}</el-radio>
          <el-radio label="其他人员">其他人员</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="ruleForm.returnName === '其他人员'" prop="returnId">
        <el-select v-model="ruleForm.returnId" filterable clearable placeholder="输入姓名、手机号搜索" :filter-method="operatorSearch" @change="operatorChange">
          <el-option
            v-for="item in operatorListCopy"
            :key="item.id"
            :label="item.usrName"
            :value="item.id"
          >
            <span style="float: left">{{ item.usrName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
          </el-option>
        </el-select></el-form-item>
      <el-form-item label="回访模板:" prop="template">
        <div class="editor">
          <editor-content class="editor__content box-y" :editor="editor" />
        </div>
      </el-form-item>
      <el-form-item label="状态:" prop="status">
        <el-radio-group v-model="ruleForm.status">
          <el-radio label="启用">启用</el-radio>
          <el-radio label="禁用">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<script>
import Dialog from '@/components/Dialog';
import { Editor, EditorContent } from 'tiptap';
export default {
  components: {
    Dialog,
    EditorContent,
  },
  data() {
    return {
      url: '',
      id: "",
      visible: false,
      title: '增加回访规则',
      editor: null,
      loading: false,
      ruleForm: {
        status: "启用",
      },
      returnVisitList: [],
      rules: {
        id: [
          { message: '请选择回访类型', trigger: 'blur', required: true },
        ],
        returnDay: [
          { message: '请输入回访时间', trigger: 'blur', required: true },
        ],
        returnName: [
          { message: '请选择回访人', trigger: 'change', required: true },
        ],
        returnId: [
          { message: '请选择回访人', trigger: 'change', required: true },
        ],
      },
      operatorList: [],
      operatorListCopy: [],
    };
  },
  methods: {
    visitRules(row) {
      const rows = JSON.parse(JSON.stringify(row));
      this.ruleForm = {
        status: "启用",
      };
      if (rows) {
        this.ruleForm = rows;
        this.$set(this.ruleForm, 'returnVisitMan', rows.tempName);
        if (rows.returnId) {
          this.$set(this.ruleForm, 'returnName', '其他人员');
          this.$set(this.ruleForm, 'operatingPersonnelName', rows.returnName);
          this.$set(this.ruleForm, 'returnId', rows.returnId);
        } else {
          this.$set(this.ruleForm, 'returnName', rows.returnName);
        }
        this.url = 'data/returnVisit/eaditReturnVisitRule';
      } else {
        this.url = "data/returnVisit/addReturnVisitRule";
      }
      this.loading = false;
      this.returnVisitTypeList();
      this.fetchAllUsr();
      this.visible = true;
      this.editor = new Editor({
        onUpdate: ({ state, getHTML, getJSON, transaction }) => {
          this.ruleForm.template = getHTML();
        },
        content: rows ? rows.template : ``,
      });
    },
    async returnVisitTypeList() {
      if (this.editor) {
        this.editor.destroy();
      }
      this.returnVisitList = [];
      const res = await this.$api['data/returnVisit/returnVisitTypeList']();
      if (res.code !== 200) return this.$message.error(res.msg);
      console.log(res.data, "规则id");
      res.data.forEach(item => {
        this.$set(item, 'returnVisitTypeId', item.id);
        this.returnVisitList.push(item);
      });
      if (!this.ruleForm.id) {
        Object.assign(this.ruleForm, this.returnVisitList[0]);
        this.id = this.ruleForm.id;
      }
    },
    // 获取全部医院人员
    async fetchAllUsr() {
      const res = await this.$api['doctor/consulting/getAllUsr']();
      if (res.code !== 200) return this.$message.error('查询操作人员失败！');
      this.operatorList = res.data;
      this.operatorListCopy = JSON.parse(JSON.stringify(this.operatorList));
    },
    close() {
      this.visible = false;
    },
    typeChange(id) {
      this.returnVisitList.forEach(item => {
        if (item.id === id) {
          Object.assign(this.ruleForm, item);
        }
      });
    },
    operatorSearch(val) {
      this.operatorListCopy = this.listHandle(val, this.operatorList);
    },
    listHandle(val, originalList) {
      let list = [];
      if (val) {
        originalList.forEach(item => {
          if (item.usrName.indexOf(val) > -1 || item.phone.indexOf(val) > -1) list.push(item);
        });
      } else {
        list = JSON.parse(JSON.stringify(originalList));
      }
      return list;
    },
    operatorChange(id) {
      if (!id) {
        this.ruleForm.operatingPersonnelName = undefined;
        return;
      }
      this.operatorList.forEach(item => {
        if (item.id === id) {
          this.ruleForm.operatingPersonnelName = item.usrName;
        }
      });
    },
    confirm() {
      this.$refs['ruleForm'].validate(async(valid) => {
        if (!valid) return;
        this.loading = true;
        if (this.ruleForm.returnName === "其他人员") {
          this.ruleForm.returnName = this.ruleForm.operatingPersonnelName;
        }
        this.ruleForm.returnRule = this.ruleForm.typeTemplate + "：第" + this.ruleForm.returnDay + "天";
        const res = await this.$api[this.url]({ ...this.ruleForm });
        this.loading = false;
        if (res.code !== 200) return this.$message.error(res.msg);
        this.$message.success("新增回访规则成功");
        this.visible = false;
        this.$emit("success");
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.editor__content{
  border: 1px solid #d3dff7;
}
.one-column{
  padding: 0 150px;
}
/deep/ .ProseMirror p{
  margin: 0;
}
.box-y{
  padding: 0 5px;
}
</style>
